#!/bin/bash

# 分布式KV服务 - 1亿记录性能测试脚本
# 适用于8核16GB内存环境 - JMeter分阶段测试配套脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置参数
SERVICE_URL="http://localhost:8080"
LOG_FILE="/tmp/performance_test_$(date +%Y%m%d_%H%M%S).log"
RESULTS_FILE="/tmp/test_results_$(date +%Y%m%d_%H%M%S).json"

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}分布式KV服务 - 1亿记录性能测试${NC}"
echo -e "${BLUE}========================================${NC}"
echo -e "测试时间: $(date)"
echo -e "服务地址: ${SERVICE_URL}"
echo -e "日志文件: ${LOG_FILE}"
echo -e "结果文件: ${RESULTS_FILE}"
echo ""

# 检查服务状态
check_service() {
    echo -e "${BLUE}检查服务状态...${NC}"
    
    if curl -s "${SERVICE_URL}/actuator/health" | grep -q "UP"; then
        echo -e "${GREEN}服务运行正常${NC}"
    else
        echo -e "${RED}服务未运行或不健康${NC}"
        exit 1
    fi
    
    # 检查内存使用
    MEMORY_INFO=$(curl -s "${SERVICE_URL}/actuator/metrics/jvm.memory.used" | grep -o '"value":[0-9]*' | cut -d':' -f2)
    echo -e "当前内存使用: $(echo "scale=2; $MEMORY_INFO/1024/1024/1024" | bc)GB"
}

# 清理测试数据
cleanup_data() {
    echo -e "${BLUE}清理测试数据...${NC}"
    
    curl -X DELETE "${SERVICE_URL}/api/test/cleanup" \
        -H "Content-Type: application/json" \
        >> ${LOG_FILE} 2>&1
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}测试数据清理完成${NC}"
    else
        echo -e "${YELLOW}数据清理失败，继续测试${NC}"
    fi
}

# 阶段1：1000万记录测试
test_phase1() {
    echo -e "${BLUE}阶段1：1000万记录测试${NC}"
    
    local start_time=$(date +%s)
    
    # 生成数据
    echo "生成1000万条记录..."
    curl -X POST "${SERVICE_URL}/api/test/generate" \
        -H "Content-Type: application/json" \
        -d '{
            "count": 10000000,
            "batchSize": 5000,
            "concurrentThreads": 20,
            "keyPrefix": "phase1_"
        }' >> ${LOG_FILE} 2>&1
    
    local generation_time=$(($(date +%s) - start_time))
    echo -e "${GREEN}✓ 数据生成完成，耗时: ${generation_time}秒${NC}"
    
    # 性能测试
    echo "执行性能测试..."
    local perf_start=$(date +%s)
    
    curl -X POST "${SERVICE_URL}/api/test/performance" \
        -H "Content-Type: application/json" \
        -d '{
            "testType": "READ_WRITE_MIX",
            "duration": 300,
            "concurrency": 50,
            "readRatio": 0.8,
            "keyRange": {
                "start": 1,
                "end": 10000000
            }
        }' >> ${LOG_FILE} 2>&1
    
    local perf_time=$(($(date +%s) - perf_start))
    echo -e "${GREEN}✓ 阶段1测试完成，耗时: ${perf_time}秒${NC}"
    
    # 记录结果
    echo "{\"phase\": 1, \"records\": 10000000, \"generation_time\": ${generation_time}, \"test_time\": ${perf_time}}" >> ${RESULTS_FILE}
}

# 阶段2：5000万记录测试
test_phase2() {
    echo -e "${BLUE}阶段2：5000万记录测试${NC}"
    
    local start_time=$(date +%s)
    
    # 生成额外的4000万条记录
    echo "生成额外4000万条记录..."
    curl -X POST "${SERVICE_URL}/api/test/generate" \
        -H "Content-Type: application/json" \
        -d '{
            "count": 40000000,
            "batchSize": 5000,
            "concurrentThreads": 30,
            "keyPrefix": "phase2_",
            "startId": 10000001
        }' >> ${LOG_FILE} 2>&1
    
    local generation_time=$(($(date +%s) - start_time))
    echo -e "${GREEN}✓ 数据生成完成，耗时: ${generation_time}秒${NC}"
    
    # 性能测试
    echo "执行性能测试..."
    local perf_start=$(date +%s)
    
    curl -X POST "${SERVICE_URL}/api/test/performance" \
        -H "Content-Type: application/json" \
        -d '{
            "testType": "READ_WRITE_MIX",
            "duration": 600,
            "concurrency": 80,
            "readRatio": 0.8,
            "keyRange": {
                "start": 1,
                "end": 50000000
            }
        }' >> ${LOG_FILE} 2>&1
    
    local perf_time=$(($(date +%s) - perf_start))
    echo -e "${GREEN}✓ 阶段2测试完成，耗时: ${perf_time}秒${NC}"
    
    # 记录结果
    echo "{\"phase\": 2, \"records\": 50000000, \"generation_time\": ${generation_time}, \"test_time\": ${perf_time}}" >> ${RESULTS_FILE}
}

# 阶段3：1亿记录测试
test_phase3() {
    echo -e "${BLUE}阶段3：1亿记录测试${NC}"
    
    local start_time=$(date +%s)
    
    # 生成额外的5000万条记录
    echo "生成额外5000万条记录..."
    curl -X POST "${SERVICE_URL}/api/test/generate" \
        -H "Content-Type: application/json" \
        -d '{
            "count": 50000000,
            "batchSize": 5000,
            "concurrentThreads": 40,
            "keyPrefix": "phase3_",
            "startId": 50000001
        }' >> ${LOG_FILE} 2>&1
    
    local generation_time=$(($(date +%s) - start_time))
    echo -e "${GREEN}✓ 数据生成完成，耗时: ${generation_time}秒${NC}"
    
    # 性能测试
    echo "执行性能测试..."
    local perf_start=$(date +%s)
    
    curl -X POST "${SERVICE_URL}/api/test/performance" \
        -H "Content-Type: application/json" \
        -d '{
            "testType": "READ_WRITE_MIX",
            "duration": 900,
            "concurrency": 100,
            "readRatio": 0.8,
            "keyRange": {
                "start": 1,
                "end": 100000000
            }
        }' >> ${LOG_FILE} 2>&1
    
    local perf_time=$(($(date +%s) - perf_start))
    echo -e "${GREEN}✓ 阶段3测试完成，耗时: ${perf_time}秒${NC}"
    
    # 记录结果
    echo "{\"phase\": 3, \"records\": 100000000, \"generation_time\": ${generation_time}, \"test_time\": ${perf_time}}" >> ${RESULTS_FILE}
}

# 专项性能测试
specialized_tests() {
    echo -e "${BLUE}专项性能测试${NC}"
    
    # 热点数据测试
    echo "热点数据测试..."
    curl -X POST "${SERVICE_URL}/api/test/hot-keys" \
        -H "Content-Type: application/json" \
        -d '{
            "hotKeyCount": 10000,
            "accessTimes": 1000,
            "concurrency": 50
        }' >> ${LOG_FILE} 2>&1
    
    # 范围查询测试
    echo "范围查询测试..."
    curl -X POST "${SERVICE_URL}/api/test/range-query" \
        -H "Content-Type: application/json" \
        -d '{
            "startId": 1,
            "endId": 100000000,
            "pageSize": 1000,
            "concurrency": 20
        }' >> ${LOG_FILE} 2>&1
    
    # 批量操作测试
    echo "批量操作测试..."
    curl -X POST "${SERVICE_URL}/api/test/batch-operations" \
        -H "Content-Type: application/json" \
        -d '{
            "batchSize": 10000,
            "batchCount": 1000,
            "concurrency": 10
        }' >> ${LOG_FILE} 2>&1
    
    echo -e "${GREEN}✓ 专项测试完成${NC}"
}

# 系统监控
monitor_system() {
    echo -e "${BLUE}系统监控${NC}"
    
    # JVM内存使用
    echo "JVM内存监控..."
    curl -s "${SERVICE_URL}/actuator/metrics/jvm.memory.used" >> ${LOG_FILE}
    curl -s "${SERVICE_URL}/actuator/metrics/jvm.memory.max" >> ${LOG_FILE}
    
    # GC统计
    echo "GC统计..."
    curl -s "${SERVICE_URL}/actuator/metrics/jvm.gc.pause" >> ${LOG_FILE}
    
    # 缓存统计
    echo "缓存统计..."
    curl -s "${SERVICE_URL}/actuator/metrics/cache.gets" >> ${LOG_FILE}
    curl -s "${SERVICE_URL}/actuator/metrics/cache.puts" >> ${LOG_FILE}
    
    # 数据库连接池
    echo "连接池监控..."
    curl -s "${SERVICE_URL}/actuator/metrics/hikaricp.connections" >> ${LOG_FILE}
    
    echo -e "${GREEN}✓ 监控数据收集完成${NC}"
}

# 生成测试报告
generate_report() {
    echo -e "${BLUE}生成测试报告...${NC}"
    
    local report_file="/tmp/performance_report_$(date +%Y%m%d_%H%M%S).html"
    
    cat > ${report_file} << EOF
<!DOCTYPE html>
<html>
<head>
    <title>分布式KV服务 - 1亿记录性能测试报告</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .header { background-color: #f0f0f0; padding: 20px; border-radius: 5px; }
        .section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        .success { color: green; }
        .warning { color: orange; }
        .error { color: red; }
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <div class="header">
        <h1>分布式KV服务 - 1亿记录性能测试报告</h1>
        <p>测试时间: $(date)</p>
        <p>测试环境: 12GB内存，华为云EulerOS 2.0</p>
    </div>
    
    <div class="section">
        <h2>测试概要</h2>
        <ul>
            <li>总记录数: 100,000,000条</li>
            <li>测试阶段: 3个阶段（1000万、5000万、1亿）</li>
            <li>数据分层: 热数据(Redis+Guava)、温数据(Cassandra+Redis)、冷数据(Cassandra)</li>
            <li>并发测试: 最高100并发</li>
        </ul>
    </div>
    
    <div class="section">
        <h2>阶段测试结果</h2>
        <table>
            <tr>
                <th>阶段</th>
                <th>记录数</th>
                <th>数据生成时间</th>
                <th>性能测试时间</th>
                <th>状态</th>
            </tr>
EOF

    # 读取测试结果
    if [ -f ${RESULTS_FILE} ]; then
        while IFS= read -r line; do
            phase=$(echo $line | grep -o '"phase":[0-9]*' | cut -d':' -f2)
            records=$(echo $line | grep -o '"records":[0-9]*' | cut -d':' -f2)
            gen_time=$(echo $line | grep -o '"generation_time":[0-9]*' | cut -d':' -f2)
            test_time=$(echo $line | grep -o '"test_time":[0-9]*' | cut -d':' -f2)
            
            echo "            <tr>" >> ${report_file}
            echo "                <td>阶段${phase}</td>" >> ${report_file}
            echo "                <td>$(printf "%'d" $records)</td>" >> ${report_file}
            echo "                <td>${gen_time}秒</td>" >> ${report_file}
            echo "                <td>${test_time}秒</td>" >> ${report_file}
            echo "                <td class=\"success\">完成</td>" >> ${report_file}
            echo "            </tr>" >> ${report_file}
        done < ${RESULTS_FILE}
    fi
    
    cat >> ${report_file} << EOF
        </table>
    </div>
    
    <div class="section">
        <h2>性能指标</h2>
        <p>详细的性能指标请查看日志文件: ${LOG_FILE}</p>
        <p>Prometheus指标: <a href="${SERVICE_URL}/actuator/prometheus">${SERVICE_URL}/actuator/prometheus</a></p>
    </div>
    
    <div class="section">
        <h2>系统资源使用</h2>
        <p>内存使用情况、GC统计、缓存命中率等详细信息请查看监控数据。</p>
    </div>
    
    <div class="section">
        <h2>建议和优化</h2>
        <ul>
            <li>根据实际查询模式调整缓存策略</li>
            <li>监控GC频率，必要时调整JVM参数</li>
            <li>根据热点数据分布优化数据分层</li>
            <li>考虑增加Cassandra节点以提高并发能力</li>
        </ul>
    </div>
</body>
</html>
EOF

    echo -e "${GREEN}✓ 测试报告生成完成: ${report_file}${NC}"
}

# 主函数
main() {
    case "$1" in
        "full")
            check_service
            cleanup_data
            test_phase1
            test_phase2
            test_phase3
            specialized_tests
            monitor_system
            generate_report
            echo -e "${GREEN}========================================${NC}"
            echo -e "${GREEN}完整测试完成！${NC}"
            echo -e "${GREEN}========================================${NC}"
            ;;
        "phase1")
            check_service
            cleanup_data
            test_phase1
            monitor_system
            ;;
        "phase2")
            check_service
            test_phase2
            monitor_system
            ;;
        "phase3")
            check_service
            test_phase3
            monitor_system
            ;;
        "specialized")
            check_service
            specialized_tests
            monitor_system
            ;;
        "monitor")
            check_service
            monitor_system
            ;;
        "cleanup")
            cleanup_data
            ;;
        "report")
            generate_report
            ;;
        *)
            echo "用法: $0 {full|phase1|phase2|phase3|specialized|monitor|cleanup|report}"
            echo ""
            echo "命令说明:"
            echo "  full        - 执行完整的1亿记录测试"
            echo "  phase1      - 执行阶段1测试（1000万记录）"
            echo "  phase2      - 执行阶段2测试（5000万记录）"
            echo "  phase3      - 执行阶段3测试（1亿记录）"
            echo "  specialized - 执行专项性能测试"
            echo "  monitor     - 收集系统监控数据"
            echo "  cleanup     - 清理测试数据"
            echo "  report      - 生成测试报告"
            echo ""
            echo "示例:"
            echo "  $0 full     # 执行完整测试"
            echo "  $0 phase1   # 仅测试1000万记录"
            echo "  $0 monitor  # 收集监控数据"
            exit 1
            ;;
    esac
}

main "$@"